package com.yyw.gulimall.elasticsearch.service.product.impl;

import com.alibaba.fastjson.JSON;
import com.yyw.common.constant.search.product.ProductEnum;
import com.yyw.common.to.productsearch.SpuInfoTo;
import com.yyw.gulimall.elasticsearch.config.RestHighLevelClientConfig;
import com.yyw.gulimall.elasticsearch.service.product.ProductSearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author 易煜玮
 * @ClassName ProductSearchServiceImpl.java
 * @Description 商品搜索服务
 * @createTime 2020年11月24日 19:08:00
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
public class ProductSearchServiceImpl implements ProductSearchService {

    private final RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean saveSkuInfo(List<SpuInfoTo> spuInfoToList) throws IOException {
        Boolean falg = false;
        BulkRequest bulkRequest = new BulkRequest(ProductEnum.PRODUCT_SEARCH_NAME.getName());
        if (!CollectionUtils.isEmpty(spuInfoToList)) {
            spuInfoToList.forEach(e -> {
                IndexRequest indexRequest = new IndexRequest().id(e.getSkuId().toString());
                String source = JSON.toJSONString(e);
                indexRequest.source(source, XContentType.JSON);
                bulkRequest.add(indexRequest);
            });
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RestHighLevelClientConfig.COMMON_OPTIONS);
            if (!bulk.hasFailures()) {
                falg = true;
                return falg;
            }
            for (BulkItemResponse item : bulk.getItems()) {
                if (item.isFailed()) {
                    log.error("保存{}号发生了错误,错误信息: {}", item.getId(), item.getFailureMessage());
                }
            }
        }
        return falg;
    }
}
